<template>
  <div v-loading="loading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading">
    <el-form :model="advancedForm" label-width="90px" class="search-form">
      <!-- 查询指标 -->
      <el-form-item label="查询指标">
        <el-radio-group v-model="orderField" size="small" class="maincol">
          <el-radio label="hs">按商品查询</el-radio>
          <el-radio label="country">按贸易伙伴查询</el-radio>
          <el-radio label="port">按收发货地区查询</el-radio>
          <el-radio label="mode">按贸易方式查询</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 按“贸易方式”优先 -->
      <template v-if="orderField === 'mode'">
        <!-- 与之前相同的 mode 逻辑 -->
        <el-form-item label="贸易方式">
          <el-select
            v-model="advancedForm.tradeType"
            placeholder="请选择贸易方式"
            clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small"
          >
            <el-option v-for="item in TradeDetailTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品">
          <el-popover v-model:visible="showHsTree" trigger="manual" placement="right-start" :width="650" :height="350">
            <div class="hs-popover-content">
              <Hstree @selection-change="onHsselection" />
            </div>
            <template #reference>
              <el-switch v-model="showHsTree" active-text="选择HS编码" size="small" />
            </template>
          </el-popover>
          <el-popover class="box-item" placement="right" :width="280">
            <template #reference>
              <el-button type="text" class="btn-small"> 已选HS编码 </el-button>
            </template>
            <div class="selected-hs-popover">
              <div v-if="SonhsData.length === 0" class="empty-tip">暂无已选HS编码</div>
              <div v-else class="hs-list">
                <div v-for="(item, index) in SonhsData" :key="index" class="hs-item">{{ item.label }}</div>
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="贸易伙伴">
          <el-select v-model="advancedForm.partner" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in PartnerTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="收发货地址">
          <el-select v-model="advancedForm.address" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in AdressTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
      </template>

      <!-- 按“HS”优先 -->
      <template v-else-if="orderField === 'hs'">
        <!-- 与之前相同的 hs 逻辑 -->
        <el-form-item label="商品">
          <el-popover v-model:visible="showHsTree" trigger="manual" placement="right-start" :width="650" :height="350">
            <div class="hs-popover-content">
              <Hstree @selection-change="onHsselection" />
            </div>
            <template #reference>
              <el-input readonly clearable :value="SonhsData.map(i => i.label).join(', ')" placeholder="请选择 HS 编码" class="hs-input" @click="showHsTree = true" @clear="SonhsData = []">
                <template #suffix><el-icon><ArrowDown /></el-icon></template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="贸易伙伴">
          <el-select v-model="advancedForm.partner" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in PartnerTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="收发货地址">
          <el-select v-model="advancedForm.address" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in AdressTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="贸易方式">
          <el-select v-model="advancedForm.tradeType" placeholder="请选择贸易方式" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in TradeDetailTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
      </template>

      <!-- 按“贸易伙伴”优先 -->
      <template v-else-if="orderField === 'country'">
        <el-form-item label="贸易伙伴">
          <el-select v-model="advancedForm.partner" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in PartnerTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品">
          <el-popover v-model:visible="showHsTree" trigger="manual" placement="right-start" :width="650" :height="350">
            <div class="hs-popover-content">
              <Hstree @selection-change="onHsselection" />
            </div>
            <template #reference>
              <el-input readonly clearable :value="SonhsData.map(i => i.label).join(', ')" placeholder="请选择 HS 编码" class="hs-input" @click="showHsTree = true" @clear="SonhsData = []">
                <template #suffix><el-icon><ArrowDown /></el-icon></template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="收发货地址">
          <el-select v-model="advancedForm.address" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in AdressTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="贸易方式">
          <el-select v-model="advancedForm.tradeType" placeholder="请选择贸易方式" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in TradeDetailTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
      </template>

      <!-- 按“收发货地”优先 -->
      <template v-else-if="orderField === 'port'">
        <el-form-item label="收发货地址">
          <el-select v-model="advancedForm.address" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in AdressTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品">
          <el-popover v-model:visible="showHsTree" trigger="manual" placement="right-start" :width="650" :height="350">
            <div class="hs-popover-content">
              <Hstree @selection-change="onHsselection" />
            </div>
            <template #reference>
              <el-input readonly clearable :value="SonhsData.map(i => i.label).join(', ')" placeholder="请选择 HS 编码" class="hs-input" @click="showHsTree = true" @clear="SonhsData = []">
                <template #suffix><el-icon><ArrowDown /></el-icon></template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="贸易伙伴">
          <el-select v-model="advancedForm.partner" placeholder="请选择国家/地区" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in PartnerTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="贸易方式">
          <el-select v-model="advancedForm.tradeType" placeholder="请选择贸易方式" clearable multiple collapse-tags collapse-tags-tooltip filterable class="select-small">
            <el-option v-for="item in TradeDetailTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
      </template>

      <!-- 通用：时间范围 -->
      <el-form-item label="起止时间">
        <div class="date-type-group">
          <el-radio-group v-model="advancedForm.dateMode" size="small">
            <el-radio label="year">按年</el-radio>
            <el-radio label="month">按月</el-radio>
          </el-radio-group>
        </div>
        <div class="date-pickers">
          <el-date-picker
            v-for="(field, idx) in advancedDateFields"
            :key="field"
            v-model="advancedForm[field]"
            :type="advancedForm.dateMode"
            :placeholder="advancedPickerPlaceholders[idx]"
            :disabled-date="disabledAdvancedDate"
            class="date-picker"
          />
        </div>
      </el-form-item>

      <!-- 通用：进出口类型 -->
      <el-form-item label="进出口类型">
        <el-select v-model="advancedForm.type" multiple clearable placeholder="请选择" class="select-small">
          <el-option v-for="item in tradeTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
        </el-select>
      </el-form-item>

      <!-- 通用：计算方式 -->
      <el-form-item label="计算方式">
        <el-select v-model="advancedForm.statisticsType" multiple clearable placeholder="请选择" class="select-small">
          <el-option v-for="item in calculationTypeOptions" :key="item.code" :label="item.label" :value="item.code" />
        </el-select>
      </el-form-item>

      <!-- 通用：其他数值 -->
      <el-form-item label="其他数值">
        <el-checkbox-group v-model="advancedForm.others">
          <el-checkbox v-for="item in checkList" :key="item.code" :label="item.label" :value="item.code" class="checkbox-small" />
        </el-checkbox-group>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="form-actions">
        <el-button @click="onAdvancedReset">取消</el-button>
        <el-button type="primary" @click="onAdvancedConfirm">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { QueryDataApi } from '../../api/Data'
import {
  toYearDate,
  toMonthDate,
  formatYear,
  formatYearMonth
} from '../../utils/dateUtils'
import Hstree from './CHHstree.vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { useReportStore } from '../../stores/dataList.js'
const store = useReportStore()
import {bus} from '../../utils/bus'
// Loading 状态
const loading = ref(true)

const emit = defineEmits(['macro-search', 'detail-search'])

// 表单数据
const advancedForm = ref({
  tradeType: [],
  dateMode: 'year',
  yearStart: null,
  yearEnd: null,
  yearMonthStart: null,
  yearMonthEnd: null,
  hsCode: '',
  partner: [],
  address: [],
  type: '',
  others: [],
  statisticsType: [],
  pageNum: 1,
  pageSize: 20
})

// 查询指标
const orderField = ref('hs')

// 选项列表
const TradeDetailTypeOptions = ref([])
const PartnerTypeOptions = ref([])
const AdressTypeOptions = ref([])
const tradeTypeOptions = ref([])
const calculationTypeOptions = ref([])
const checkList = ref([])

// HS 选择
const showHsTree = ref(false)
const SonhsData = ref([])

// 时间范围
let minYear, maxYear, minYearMonth, maxYearMonth

const disabledAdvancedDate = (date) => {
  const y = date.getFullYear()
  if (advancedForm.value.dateMode === 'year') {
    return y < minYear || y > maxYear
  }
  const code = y * 100 + date.getMonth() + 1
  return code < minYearMonth || code > maxYearMonth
}

const advancedDateFields = computed(() =>
  advancedForm.value.dateMode === 'year'
    ? ['yearStart', 'yearEnd']
    : ['yearMonthStart', 'yearMonthEnd']
)
const advancedPickerPlaceholders = computed(() =>
  advancedForm.value.dateMode === 'year'
    ? ['开始年份', '结束年份']
    : ['开始月份', '结束月份']
)

function onHsselection(list) {
  SonhsData.value = list
}

function onAdvancedConfirm() {
  const payload = {
    mainCol: orderField.value,
    timeType: advancedForm.value.dateMode,
    timeStart:
      advancedForm.value.dateMode === 'year'
        ? formatYear(advancedForm.value.yearStart)
        : formatYearMonth(advancedForm.value.yearMonthStart),
    timeEnd:
      advancedForm.value.dateMode === 'year'
        ? formatYear(advancedForm.value.yearEnd)
        : formatYearMonth(advancedForm.value.yearMonthEnd),
    exIm: advancedForm.value.type ? advancedForm.value.type : [],
    mode: advancedForm.value.tradeType ? advancedForm.value.tradeType : [],
    country: advancedForm.value.partner ? advancedForm.value.partner : [],
    port: advancedForm.value.address ? advancedForm.value.address : [],
    dataCol: advancedForm.value.others,
    statisticsType: advancedForm.value.statisticsType,
    hs: SonhsData.value.map((i) => i.code),
    pageNum: 1,
    pageSize: 20
  }

  // QueryDataApi.ChinDetailSearch(payload).then(res => {
  //   store.add('chinaSeniorList', res.data.chinaSeniorList)
  //   console.log(res)
  // })

  bus.emit('detail-search', { params: payload, api: 'ChinDetailSearch', prop: 'chinaSeniorList' })
}

function onAdvancedReset() {
  advancedForm.value = {
    tradeType: [],
    dateMode: 'year',
    yearStart: toYearDate(maxYear),
    yearEnd: toYearDate(maxYear),
    yearMonthStart: toMonthDate(maxYearMonth),
    yearMonthEnd: toMonthDate(maxYearMonth),
    hsCode: '',
    partner: [],
    address: [],
    type: '',
    others: [],
    statisticsType: [],
    pageNum: 1,
    pageSize: 20
  }
  SonhsData.value = []
  orderField.value = 'hs'
}

onMounted(() => {
  loading.value = true
  // 并发请求所有数据接口
  const promises = [
    QueryDataApi.getDate().then(res => {
      const d = res.data.timeRangeChina
      minYear = d.yearStart; maxYear = d.yearEnd
      minYearMonth = d.yearMonthStart; maxYearMonth = d.yearMonthEnd
      advancedForm.value.yearStart = toYearDate(maxYear)
      advancedForm.value.yearEnd = toYearDate(maxYear)
      advancedForm.value.yearMonthStart = toMonthDate(maxYearMonth)
      advancedForm.value.yearMonthEnd = toMonthDate(maxYearMonth)
    }),
    QueryDataApi.getTradeDetailType().then(res => { TradeDetailTypeOptions.value = Object.values(res.data.mode || {}) }),
    QueryDataApi.getPartnerType().then(res => { PartnerTypeOptions.value = Object.values(res.data.country || {}) }),
    QueryDataApi.getAddressType().then(res => { AdressTypeOptions.value = Object.values(res.data.port || {}) }),
    QueryDataApi.getTradeType().then(res => { tradeTypeOptions.value = Object.values(res.data.exIm || {}) }),
    QueryDataApi.getCalculationType().then(res => { calculationTypeOptions.value = Object.values(res.data.statisticsType || {}) }),
    QueryDataApi.getOtherType().then(res => { checkList.value = Object.values(res.data.dataCol || {}) })
  ]
  Promise.all(promises)
    .finally(() => {
      // 结束加载
      loading.value = false  
    })

})
</script>

<style lang="scss" scoped>
.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.date-type-group {
  margin-bottom: 4px;
  .el-radio__label {
    font-size: 12px;
  }
}

.date-pickers {
  display: flex;
  gap: 8px;
  align-items: center;
  width: 100%;
}

.date-picker {
  width: 160px; /* 缩小日期框 */
  font-size: 12px; /* 调小日期选择器字体 */
}

.select-small {
  font-size: 12px;
}

.btn-small {
  font-size: 12px;
  padding: 4px 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}

.selected-hs-popover {
  max-height: 280px;
  overflow-y: auto;
  padding: 6px;
}

.hs-popover-content {
  padding: 6px;
}

.hc-item {
  padding: 4px 10px;
  margin: 3px 0;
  background: #f5f7fa;
  border-radius: 4px;
}

.hs-input {
  width: 100%;
}

.selected-time {
  margin-top: 6px;
  font-size: 14px;
  color: #409eff;
}
</style>
